package org.room402.framework.chat.container;

import cn.hutool.core.util.StrUtil;
import org.room402.constant.system.ErrorCode;
import org.room402.entity.chat.ChatPool;
import org.room402.entity.chat.UserSession;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ChatPoolContainer {
    ConcurrentHashMap<String, ChatPool> idToPool = new ConcurrentHashMap<>();

    private final AtomicInteger atomicInteger = new AtomicInteger();

    /**
     * 创建一个池
     */
    public ChatPool create(UserSession userSession, String name) {
        name = StrUtil.isBlank(name) ? "聊天池" + userSession.getCreatedPoolIds().size() : name;
        ChatPool chatPool = ChatPool.form(userSession, name, getId());
        chatPool.add(userSession);
        idToPool.put(chatPool.getId(), chatPool);
        return chatPool;
    }

    public boolean isInPool(String poolId, UserSession userSession) {
        ChatPool pool = validPool(poolId);
        return pool.getMembers().stream()
                .anyMatch(userInfoView -> userInfoView.getId().equals(userSession.getId()));
    }

    /**
     * 用户入池
     */
    public ChatPool inPool(String poolId, UserSession userSession) {
        ChatPool chatPool = validPool(poolId);
        chatPool.add(userSession);
        return chatPool;
    }

    private ChatPool validPool(String poolId) {
        ChatPool chatPool = idToPool.get(poolId);
        if (Objects.isNull(chatPool)) {
            ErrorCode.CHAT_POOL_NOT_FOUND.throwException();
        }
        return chatPool;
    }

    /**
     * 解散聊天池
     */
    public ChatPool remove(String poolId) {
        return idToPool.remove(poolId);
    }


    /**
     * 获得唯一ID
     */
    private String getId() {
        return StrUtil.fillBefore(String.valueOf(atomicInteger.incrementAndGet()), '0', 4);
    }

    public ChatPool get(String targetId) {
        return idToPool.get(targetId);
    }
}
